const { Op } = require("sequelize");
const Sequelize = require('sequelize');
var COS = require('cos-nodejs-sdk-v5');

const artPPTModel = appRequire('models/artPPT');
const collectModel = appRequire('models/collect');
const orderModel = appRequire('models/order');
const userModel = appRequire('models/user');
const downLoadModel = appRequire('models/downLoad');

// 导出对象，供其它模块调用
module.exports = {
    list,
    save,
    destroy,
    detail,
    changeStatusOff
};

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    /*let courses = await artPPTModel.update({
        status:false,
    },{
        where: {
            createdAt:{[Op.lt]: "2023-05-01 23:59:59"}
        }
    })

    console.log(courses)*/

    let params = {}
    let orders = [['createdAt', 'DESC']]
    if (postData.classDesc && postData.classDesc != '全部') params.classDesc = postData.classDesc
    if (postData.typeDesc) params.typeDesc = postData.typeDesc
    if (postData.isNice) params.isNice = postData.isNice
    if (postData.fileType) params.fileType = postData.fileType //资源类型

    if (postData.order) {
        if (postData.order.indexOf("-") == -1) {
            orders = [[postData.order, 'ASC']]
        } else {
            orders = [[postData.order.split("-")[1], 'DESC']]
        }
    }
    if (postData.searchText) {
        params[Op.or] = [
            { title: { [Op.like]: '%' + postData.searchText + '%' } },
            { desc: { [Op.like]: '%' + postData.searchText + '%' } },
            { fileUrls: { [Op.substring]: '%' + postData.searchText + '%' } },
        ]
    }
    if (postData.status == "未审核") params.status = 0
    if (postData.status == "已审核") params.status = 1
    let course = await artPPTModel.findAndCountAll({
        where: params,
        order: orders,
        limit: postData.pageSize,
        offset: postData.pageSize * (postData.pageNum - 1),
        include: ["typeDesc", "class"]
    })
    course = Common.clone(course)

    for (let item of course.rows) {
        //console.log(item.getType)
        if (item.typeDesc && item.typeDesc.name) item.typeDesc = item.typeDesc.name
        ///if (item.class && item.class.name) item.classDesc = item.class.name

        if (item.images && item.images.length == 0 && item.classDesc != '课程' && item.fileUrls.length > 0) {
            item.images.push(item.fileUrls[0].fileUrl + '?ci-process=doc-preview&dstType=png&scale=20');
        }
        if (item.typeDesc && item.typeDesc.name) item.typeDesc = item.typeDesc.name;
        //delete item.fileUrls
    }

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}

//ppt详情
async function detail(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        },
        include: ["class"]
        //attributes: ["objectId", "number", "price", "title", "desc", "content", "downLoadNum", "classDesc", "tags", "images", "videoUrl", "createdAt"]
    })
    course = Common.clone(course)
    //course.images = [course.fileUrls[0].fileUrl + '?ci-process=doc-preview&dstType=png&scale=40']
    //course.fileUrl = course.fileUrls[0].fileUrl
    if (course.class && course.class.name) course.classDesc = course.class.name

    //delete course.pptUrl
    returnData.data = course
    delete returnData.data.pptUrl
    request.json(returnData)
}

async function save(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['title'], request);
    if (checkResult == false) return;

    let params = {
        title: postData.title,
        content: postData.content,
        desc: postData.desc,
        price: postData.price,
        typeDesc: postData.typeDesc,
        number: postData.number,
        tags: postData.tags,
        videoUrl: postData.videoUrl,
        fileUrls: postData.fileUrls,
        courceNumber: postData.courceNumber,
        //age: postData.age,
        //type: postData.type,
        page: postData.page,
        isNice: postData.isNice,
        TypeId: null,
        ClassId: null,

    }
    if (postData.sourceFrom) params.sourceFrom = postData.sourceFrom
    if (postData.getType) params.getType = postData.getType || ["广告", "付费"]
    if (postData.fileType) params.fileType = postData.fileType
    if (postData.ageMin) params.ageMin = postData.ageMin
    if (postData.size) params.size = postData.size
    if (postData.ageMax) {
        if (postData.ageMin && Number(postData.ageMax) <= Number(postData.ageMin)) {
            returnData.code = 0
            returnData.msg = "最大年龄不能小于最小年龄"
            return request.json(returnData)
        }

        params.ageMax = postData.ageMax
    }
    if (postData.age && postData.age != "通用") {
        params.ageMin = postData.age.split("~")[0]
        postData.age.split("~")[2] ? params.ageMax = postData.age.split("~")[2] : ''
    }
    if (postData.typeId) params.TypeId = postData.typeId
    if (postData.classId) params.ClassId = postData.classId
    if (postData.classDesc) params.classDesc = postData.classDesc
    if (postData.courseId) params.courseId = postData.courseId

    if (postData.statusDesc == "已审核") params.status = 1
    if (postData.statusDesc == "未审核") params.status = 0

    params.images = postData.images
    params.baiduDeskLink = postData.baiduDeskLink
    params.longImages = postData.longImages
    //params.baiduDeskImage = postData.baiduDeskImage

    if (postData.objectId) {
        let result = await artPPTModel.update(params, {
            where: {
                objectId: postData.objectId
            }
        })
        returnData.data = result
    } else {
        /*let thisResult = await artPPTModel.findOne({
            where: {
                title: postData.title,
            }
        })

        if (thisResult) {
            returnData.code = 0
            returnData.msg = "已存在此PPt"
            return request.json(returnData)
        }*/

        params.objectId = sid.uuid()
        if (postData.isAdmin) {
            params.userId = "3h4SfJjFn9J4SHA"
        } else {
            params.userId = postData.uid
        }
        if (postData.isAdmin || postData.uid == "3gYxQ9X674j8p4Z") {
            params.status = 1
        } else {
            params.status = 0
        }
        if (postData.isAdmin && postData.downLoadNum) params.downLoadNum = postData.downLoadNum
        let result = await artPPTModel.create(params)
        /*if (postData.isAdmin || postData.uid == "3gYxQ9X674j8p4Z") {
            let thisUsers = await userModel.user.findAll({
                limit: 10,
                order: [
                    [Sequelize.literal('RAND()')]
                ],
            })
            let thisArray = []
            for (let thisUser of thisUsers) {
                let thisParams = {
                    objectId: sid.uuid(),
                    userId: thisUser.objectId,
                    artpptId: result.objectId,
                }

                thisArray.push(thisParams)
            }
            await downLoadModel.downLoad.bulkCreate(thisArray);
        }*/

        returnData.data = result
    }

    // 如果是课件且有关联课程，自动更新课程的 page 字段
    if (params.courseId && postData.classDesc !== '课程') {
        // 统计该课程下的课件总数
        let coursewareCount = await artPPTModel.count({
            where: {
                courseId: params.courseId,
                classDesc: { [Op.ne]: '课程' }
            }
        })

        // 更新课程的 page 字段
        await artPPTModel.update({
            page: coursewareCount
        }, {
            where: {
                objectId: params.courseId
            }
        })
    }

    request.json(returnData)
}

async function destroy(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let thisPpt = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        }
    })
    thisPpt = Common.clone(thisPpt)

    if (thisPpt) {

        for (let fileUrl of thisPpt.fileUrls) {
            console.log(fileUrl)
            let splitWords1 = fileUrl.fileUrl.split("https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/")
            let key = splitWords1[1]

            var cos = new COS({
                SecretId: 'AKIDuc5GAnAG5duuHQJwHL8fusZz80bvykFT',
                SecretKey: 'zh8IAm7BxSgdJhpgFXZJmzvd5HDrEK9g'
            });

            cos.deleteObject({
                Bucket: 'artppt-1306121076', /* 必须 */
                Region: 'ap-nanjing',    /* 必须 */
                Key: key    /* 必须 */
            }, function (err, data) {
                console.log(err, data)
            });
        }

        let result = await artPPTModel.destroy({
            where: {
                objectId: postData.objectId
            }
        })
        returnData.data = result
        request.json(returnData)
    } else {
        returnData.code = 0
        returnData.data = course
        returnData.msg = "此课件已删除"
        return request.json(returnData)
    }
}

//下架ppt
async function changeStatusOff(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let result = await artPPTModel.update({
        status: 0
    }, {
        where: {
            objectId: postData.objectId
        }
    })
    returnData.data = result
    request.json(returnData)
}